import { Injectable } from '@angular/core';
import { RmiProvider } from '../rmi/rmi';
import { UUID } from 'angular2-uuid';
import { isNumber } from 'ionic-angular/umd/util/util';

/*
  Generated class for the CommandProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class CommandProvider {

  constructor(public rmi: RmiProvider) {
  }

  execute(command: string, parameter: any, callback: any, timeout?: number) {

    let randQueue = UUID.UUID();

    let subscribeHandler = this.rmi.subscribe(`/queue/${randQueue}`, (data) => {
      callback(data);
      if (!subscribeHandler.getIsCanceled()) {
        subscribeHandler.cancelSubscribe();
      }
    }, null);

    let timer = setTimeout(() => {
      clearTimeout(timer);
      if (!subscribeHandler.getIsCanceled()) {
        subscribeHandler.cancelSubscribe();
      }
    }, timeout);

    this.rmi.execute(`/queue/command`, null, {
      command: `${command}`,
      queue: `${randQueue}`,
      ...parameter
    });
  }

}
